<?php
/*
 * 下订单
 */
namespace Mobile\Controller;
use Mobile\Model\goodsModel;
use Mobile\Model\orderModel;
use Mobile\Model\deliveryModel;
use Mobile\Model\moneylogModel;
use Mobile\Model\cartModel;
use Mobile\Model\goodsguigeModel;//规格

class OrderaddController extends BaseController {

    public $goodsModel;
    public $orderModel;
    public $deliveryModel;

    public $moneylogModel;
    public $goodsguigeModel;
    public $gradeModel;

    
    
    public function __construct() {
        parent::__construct();
        $this->goodsModel = new goodsModel();
        $this->orderModel = new orderModel();
        $this->deliveryModel = new deliveryModel();
        $this->moneylogModel = new moneylogModel();
        $this->goodsguigeModel = new goodsguigeModel();
        $this->cartModel = new cartModel();
    }
    

    /*
     * 获取收货地址信息
     */
    protected function _get_delivery_data(){
        $allow = array(
            "delivery_name","address","delivery_mobile","province","city","county","wechat_user",
            "province_id","bill_name",'pay_password'
        );
    
        //判断是否是实物商品
        if($this->is_shiwu == 1){
            $must = array(
                "delivery_name","address","delivery_mobile","province","city","province_id"
            );
        }else{
            $must = array(
                "delivery_mobile","delivery_name"
            );
        }
        $data = $_POST;//param_filter($_POST,$allow,$must,true,true);
        if(empty($data)){
            return false;
        }
        //使用虚拟币时核验支付密码
        if(post('use_yongjin')==1 || post('use_cash')==1 || post('use_ex_cash')==1) {
            $member = $this->memberModel->where(array('uid'=>$this->uid))->find();
            if(md5($data['pay_password'])!=$member['pay_password']) {
//                return_json(1,'支付密码错误');
            }
        }

        return $data;
    }
    

    /*
     * 使用佣金
     */
    protected function _get_order_data($goods_info,$delivery_data){
        $data['delivery_name'] = $delivery_data['delivery_name'];//收货人姓名
        $data['delivery_mobile'] = $delivery_data['delivery_mobile'];//收货人电话
        $data['bill_name'] = $delivery_data['bill_name'];
        $data['delivery'] = serialize($delivery_data);//收货的地址
        
        $data['province'] = $delivery_data['province'];
        $data['city'] = $delivery_data['city'];
        $data['county'] = $delivery_data['county'];
       
        $data['khnote'] = post('khnote');//客户留言
        $data['uid'] = $this->uid;
        //$data['openid'] = $this->memberinfo['openid'];
        $data['openid'] = $this->openid;
        $data['nickname'] = $this->memberinfo['nickname'];
        $data['realname'] = $this->memberinfo['realname'];//下单人真实姓名
    
        $data['refer_uid'] = $this->memberinfo['refer_uid'];//我的上级uid
        $data['refer_nickname'] = $this->memberinfo['refer_nickname'];
        
        $data['order_sn'] = 'WX'.date("YmdHis").sprintf("%05d", $this->uid).rand(10,99);//生成订单号
    
        $data['checked'] = 0;//未支付
        $data['create_time'] = date("Y-m-d H:i:s");//创建时间
    
        $data['goods'] = serialize($goods_info);//把商品信息序列化
        $data['order_title'] = $goods_info[0]['goods_name'];//第一件商品的商品名称
    
        $money_arr = $this->_get_pay_money($goods_info);
        $goods_money= $money_arr['money'];
        $data['all_money'] = $money_arr['all_money'];
        $data['pay_orgmoney'] = $goods_money;//订单原始总价(未使用任何优惠的价格)
        $data['order_type'] = isset($_POST['order_type'])?$_POST['order_type']:0;
//        
//        if($_POST['order_type'] == 1){
//            
//            if(post('baodan_type')==1) {
//                if($goods_money<20000){
//                    return_json(1,"报单金额必须大于20000");
//                }
//            }elseif(post('baodan_type')==2) {
//                if($goods_money<50000){
//                    return_json(1,"报单金额必须大于50000");
//                }
//            }
//            
//            $data['ceo_refer'] = $_POST['refer_uid'];//新报ceo的uid
//            
//            $len = strlen($data['ceo_refer']);
//            if($len == 11){
//                $rewhere = array('mobile'=>$data['ceo_refer']);
//            }else{
//                $rewhere = array('uid'=>$data['ceo_refer']);
//            }
//            
//            $referinfo = $this->memberModel->where($rewhere)->find();
//            if(!$referinfo){
//                return_json(1,"推荐人不存在");
//            }
//        }
        $full_money = C("FULL_BAOYOU");//满1000包邮
        if($goods_money>=$full_money){
            $data['shipping'] = 0;//包邮
        }else{
            //未达到包邮条件
            if($this->is_shiwu){
                //实物
                $data['shipping'] = $this->_get_shipping($goods_info,$delivery_data['province_id']);//计算运费
            }else{
                //虚拟商品
                $data['shipping'] = 0;//包邮
            }
        }

        $shipping = $data['shipping'];//运费
        
        //使用优惠券
        //TODO
        $coupon_money = 0;//TODO
        $data['coupon_money'] = 0;
    
        $goods_money -= $data['coupon_money'];//商品费用减去优惠券
        
        $use_score =  post('use_score');
        if($use_score==1 && ($goods_money>0 || $shipping>0) && $goods_info[0]['gtype_id']==9 && count($goods_info)==1){
    
            if($this->memberinfo['score']>=$goods_money){
                if($this->memberinfo['score']>=($goods_money+$shipping)){
                    //足够支付运费
                    $data['score_money'] = $goods_money+$shipping;//
                    $shipping = 0;
                }else{
                    //不足够支付运费
                    $data['score_money'] = $this->memberinfo['score'];//使用完
                    $shipping = $shipping-($this->memberinfo['score']-$goods_money);
                }
                $goods_money = 0;
            }else{
                //不够,部分使用佣金
                $data['score_money'] = $this->memberinfo['score'];//
                $goods_money -= $this->memberinfo['score'];
            }
        }
        
    
        $use_ex_cash =  post('use_ex_cash');//是否使用佣金
        //使用佣金
        if(($goods_money>0 || $shipping>0) && ($use_ex_cash == 1)){
    
            if($this->memberinfo['ex_cash']>=$goods_money){
                //足够,全额使用佣金

                if($this->memberinfo['ex_cash']>=($goods_money+$shipping)){
                    //足够支付运费
                    $data['ex_cash'] = $goods_money+$shipping;//
                    $shipping = 0;
                }else{
                    //不足够支付运费
                    $data['ex_cash'] = $this->memberinfo['ex_cash'];//使用完
                    $shipping = $shipping-($this->memberinfo['ex_cash']-$goods_money);
                }
                $goods_money = 0;
            }else{
                //不够,部分使用佣金
                $data['ex_cash'] = $this->memberinfo['ex_cash'];//
                $goods_money -= $this->memberinfo['ex_cash'];
            }
        }

        $use_yongjin =  post('use_yongjin');//是否使用佣金
        //使用佣金
        if(($goods_money>0 || $shipping>0) && ($use_yongjin == 1)){
    
            if($this->memberinfo['money']>=$goods_money){
                //足够,全额使用佣金

                if($this->memberinfo['money']>=($goods_money+$shipping)){
                    //足够支付运费
                    $data['yongjin_money'] = $goods_money+$shipping;//
                    $shipping = 0;
                }else{
                    //不足够支付运费
                    $data['yongjin_money'] = $this->memberinfo['money'];//使用完
                    $shipping = $shipping-($this->memberinfo['money']-$goods_money);
                }
                
                $goods_money = 0;
            }else{
                //不够,部分使用佣金
                $data['yongjin_money'] = $this->memberinfo['money'];//
                $goods_money -= $this->memberinfo['money'];
            }
        }
        
        $use_prize =  post('use_prize');//是否使用佣金
        //使用奖励佣金
        if(($goods_money>0 || $shipping>0) && ($use_prize == 1)){
    
            if($this->memberinfo['prize_money']>=$goods_money){
                //足够,全额使用佣金

                if($this->memberinfo['prize_money']>=($goods_money+$shipping)){
                    //足够支付运费
                    $data['prize_money'] = $goods_money+$shipping;//
                    $shipping = 0;
                }else{
                    //不足够支付运费
                    $data['prize_money'] = $this->memberinfo['prize_money'];//使用完
                    $shipping = $shipping-($this->memberinfo['prize_money']-$goods_money);
                }
                
                $goods_money = 0;
            }else{
                //不够,部分使用佣金
                $data['prize_money'] = $this->memberinfo['prize_money'];//
                $goods_money -= $this->memberinfo['prize_money'];
            }
        }
        
    
        $use_cash =  post('use_cash');//是否使用充值币
        //使用余额
        if(($goods_money>0 || $shipping>0) && ($use_cash == 1)){
    
            if($this->memberinfo['cash_money']>=$goods_money){
                //足够,全额使用
                if($this->memberinfo['cash_money']>=($goods_money+$shipping)){
                    //足够支付运费
                    $data['cash_money'] = $goods_money+$shipping;//
                    $shipping = 0;
                }else{
                    //不足够支付运费
                    
                    $data['cash_money'] = $this->memberinfo['cash_money'];//使用完
                    $shipping = $shipping-($this->memberinfo['cash_money']-$goods_money);
                }
                
                $goods_money = 0;
            }else{
                //不够,部分使用
                $data['cash_money'] = $this->memberinfo['cash_money'];//
                $goods_money -= $this->memberinfo['cash_money'];
            }
        }
    
       
        $data['pay_nowmoney'] = $goods_money;//订单原始总价(使用优惠券,积分后的价格)
        $data['pay_money'] = $data['pay_nowmoney']+$shipping;//总的费用=优惠后的商品钱+运费
        $data['pay_money'] = round($data['pay_money'],2);//四舍五入
        
        $data['order_cashmoney'] = $this->_get_pay_cash($data);//除去折扣等后,订单中能够产生佣金的金额
    
        $data['zhekou_money'] = $data['all_money']+$data['shipping']-$data['pay_money']-$data['score_money']-$data['ex_cash']-$data['prize_money']-$data['cash_money']-$data['yongjin_money'];
        
        if($data['pay_money']<0){
            return_json(1,"商品价格出错了");//可以等于0
        }
    
        $data['order_ip'] = get_client_ip();//订单ip
        $data['is_comment'] = 0;//未评论
    
        return $data;
    }
    
    
    /*
     * 订单中需要支付佣金的钱(扣除折扣)
     */
    protected function _get_pay_cash($order){

        $pay_cash = $order['cash_money'] + $order['pay_money']+$order['yongjin_money']+$order['prize_money']-$order['shipping'];
        return $pay_cash ? $pay_cash : 0;
    
    }
    
    
    
    /*
     * 计算运费
     * TODO
     */
    public function _get_shipping($goods_info,$aid=330000){
        //计算要支付的钱
        $money = 0;
        $all_weight = 0;//订单总重量
        $s = M("express");
        $where = array(
            "province_id" => $aid
        );
        $res = $s->where($where)->find(); 
        //首重和续重
        $first = $res["first_weight"];
        $next = $res["next_weight"];
        foreach ($goods_info as $k=>$v){
            //判断是不是包邮商品
            if($v['freight_payer'] == 1){
                continue;
            }
            
            $all_weight += $v['num'] * $v['goods_weight'];
        }
        $all_weight = ceil($all_weight);

        if($all_weight == 0){
            $money = 0;
        }else if($all_weight<=1){
            $money = $first;
        }else{
            $money = $first + ($all_weight-1)*$next;
        }
        
        $money = round($money,2);//四舍五入
        return $money;
    }
    
    /*
     * 计算要支付商品的钱
     * $type订单类型0升级，1重消 2提货
     */
    protected function _get_pay_money($goods_info){
        //计算商品价格
        //等级价格

        $num = 0;//商品总量
        
        $grade_id = $this->memberinfo['grade_id'];
        $money = array();
        foreach ($goods_info as $k=>$v){
            $num += $v['num'];

            
            $money['money'] += $v['num'] * $v['shop_price'];
        }
        

        
        $money['money'] = round($money['money'],2);
        $money['all_money'] = $money['money'];
        
        return $money;
    }
    
    
    /*
     * 写支出流水,并扣除用户表里的钱
     * $mtype 1分销佣金,2重消币 ,3现金电子币 ,4重消佣金,5互助奖,6车房奖, 7领导奖, 8分红奖 ,9保证金 , 10个税 , 11提货币流水
     */
    protected function _outMoneylog($money,$order,$mtype){
        
        if($money == 0){
            return false;//金额等于0 不做任何操作
        }
        
        $uid = $order['uid'];
        
        switch($mtype){
            case 2:
                $this->memberModel->kouQian($uid,'score',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['score'];
                $this->_money_msg($userinfo, $money, 2);
                break;
            case 3:
                $this->memberModel->kouQian($uid,'cash_money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['cash_money'];
                $this->_money_msg($userinfo, $money, 3);
                break;
            case 1:
                $this->memberModel->kouQian($uid,'money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['money']+$userinfo['lock_money'];
                $this->_money_msg($userinfo, $money, 1);	
                break;
            case 12:
                $this->memberModel->kouQian($uid,'prize_money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['prize_money']+$userinfo['lockprize_money'];
                break;
            case 4:
                $this->memberModel->kouQian($uid,'stock',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['stock'];
                $this->_money_msg($userinfo, $money, 4);
                break;
            default:
                return false;
        }
        
        $money_log = array(
            "uid" => $order['uid'],
            "nickname" => $order['realname'],
            "logtype" => 0,//收入 1收入 0支出
            "mtype" => $mtype,//类型
            "money" => $money,
            "content" => "【订单消费】".$order['order_title'],
            "order_id" => $order['order_id'],
            "order_uid" => $order['uid'],
            "order_paymoney" => $order['order_cashmoney'],//订单支付的金额(需要分佣的金额)
            "order_nickname" => $order['nickname'],
            "create_time" => date("Y-m-d H:i:s"),//写流水的时间
            "un_lock" => 1,//不锁定,立即扣除 1解锁,0锁定
            "cash_money" => $yue,//查余额
        );
        
        
        $res = $this->moneylogModel->addMoneylog($money_log);
        
        return $res;

    }
    
    protected function _inMoneylog($money,$order,$mtype){
        
        if($money == 0){
            return false;//金额等于0 不做任何操作
        }
        
        $uid = $order['uid'];
        
        switch($mtype){
            case 2:
                $this->memberModel->jiaQian($uid,'score',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['score'];
                break;
            case 3:
                $this->memberModel->jiaQian($uid,'cash_money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['cash_money'];
                break;
            case 1:
                $this->memberModel->jiaQian($uid,'money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['money']+$userinfo['lock_money'];
                break;
            case 12:
                $this->memberModel->jiaQian($uid,'prize_money',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['prize_money']+$userinfo['lockprize_money'];
                break;
            case 4:
                $this->memberModel->jiaQian($uid,'stock',$money);
                $userinfo = $this->memberModel->where(array('uid'=>$uid))->find();
                $yue = $userinfo['stock'];
                break;
            default:
                return false;
        }
        
        $money_log = array(
            "uid" => $order['uid'],
            "nickname" => $order['realname'],
            "logtype" => 1,//收入 1收入 0支出
            "mtype" => $mtype,//类型
            "money" => $money,
            "content" => "补货订单".$order['order_title'],
            "order_id" => $order['order_id'],
            "order_uid" => $order['uid'],
            "order_paymoney" => $order['order_cashmoney'],//订单支付的金额(需要分佣的金额)
            "order_nickname" => $order['nickname'],
            "create_time" => date("Y-m-d H:i:s"),//写流水的时间
            "un_lock" => 1,//不锁定,立即扣除 1解锁,0锁定
            "cash_money" => $yue,//查余额
        );
        
        $res = $this->moneylogModel->addMoneylog($money_log);
        
        return $res;

    }
    
    
    /*
     * 扣除微币,并发送微信模板消息通知
     */
    protected function _kou_score($order,$memberinfo){

        //$mtype 1分销佣金,2重消币 3现金电子币  4重消佣金 5互助奖6车房奖7领导奖8分红奖 9保证金 10个税
        //现金币
        $this->_outMoneylog($order['cash_money'],$order,3);
        
        //佣金TODO:区分重消佣金,分销佣金
        $this->_outMoneylog($order['yongjin_money'],$order,1);
        
        $this->_outMoneylog($order['prize_money'],$order,12);
        
        $this->_outMoneylog($order['ex_cash'],$order,4);
        
        $this->_outMoneylog($order['score_money'],$order,2);

        return true;
    }
    

    
    
    /*
     * 创建订单
     */
    public function index(){
        //我的等级id
        $grade_id = $this->memberinfo['grade_id'];
        
        $gid_arr = post('checkbox');//商品id数组
        $guige_arr = post('guige_id');//商品规格
        
        $guige_arr_id = post('guige_id_new');//新的商品规格id
        $guige_arr_name = post('guige_name_new');//新的商品规格name
    
        if(empty($gid_arr)){
            return_json(1,"请点击商品左侧小圆点勾选商品");
        }
        $num_str = post("num");
        $num_arr = explode("_", $num_str);
        //查看一共购买了多少商品
        $num_all = 0;
        foreach ($num_arr as $kk=>$vv){
            $num_all +=$vv;//总的商品数
        }
        $noyongjin_money = 0;//不分佣金的特殊金额
        $goods_info = array();
        
        //组装商品信息
        foreach($gid_arr as $k=>$v){
            $v = intval($v);//商品id
            //查找商品
            $where  = array(
                "goods_id" => $v,
                "ischeck" => 1,
                "stock" => array('gt',0)
            );
            $g_res = $this->goodsModel->getGoods($where);
            if(empty($g_res)){
                //商品为空
                continue;
            }
            //商品数量
            $nums = intval($num_arr[$k]);
            $nums = $nums ? $nums : 1;
            $g_res['num'] = $nums;
            //查看库存够不够
            if($g_res['stock'] <$nums){
                continue;
            }
            //过滤掉无用数据
            unset($g_res['goods_desc']);
            unset($g_res['goods_thumb']);
            unset($g_res['create_time']);
            unset($g_res['ischeck']);
            unset($g_res['sale_basic']);
            unset($g_res['sale_real']);
            unset($g_res['sale_all']);
            unset($g_res['is_new']);
            unset($g_res['is_hot']);
            unset($g_res['all_views']);
            //商品规格
            $guige_id = intval($guige_arr[$k]);
            $guige_id =  $guige_id ? $guige_id : '';

            $g_res['guige_id'] = $guige_arr_id[$k];
            $g_res['guige_name'] = $guige_arr_name[$k];
           
            //判断商品规格是否可以购买
            if($guige_id){
                $where_guige = array(
                    "guige_id" => $guige_id
                );
                $guige_info = $this->goodsguigeModel->getGoodsguige($where_guige);
                if(empty($guige_info)){
                    //当前规格不存在
                    continue;
                }
                //判断规格库存
                //查看库存够不够
                if($guige_info['guige_stock'] < $nums){
                    continue;//库存不够
                }
    
                //判断价格 todo
                $g_res['guige_name'] = $guige_info['guige_size'];//todo
                if($guige_info['guige_color']){
                    $g_res['guige_name'] = $guige_info['guige_size']." ".$guige_info['guige_color'];//todo
                }
    
            }
            $g_res['shop_price'] = $g_res['grade'.$grade_id.'_price'];
            $goods_info[] = $g_res;//获取可以购买的商品
        }
    
        if(empty($goods_info)){
            return_json(1,"该商品已下架","","/mobile/goods/lists");
        }

        //再次获取最新的用户信息
        $memberinfo = $this->getMemberInfobyUid($this->uid);
        $this->updateMemberSession();
    
        $this->is_shiwu = 0;
        $sj_gnums=0;
        //再次遍历商品,逻辑判断
        foreach ($goods_info as $k=>$v){
            //商品id
            $goods_ids[] = $v['goods_id'];
            $goods_names[] = $v['goods_bianhao'].$v['goods_name'];
            $goods_sale[] = $v['goods_id'].",".$v['num'];//拼接编号和售出数量，用作统计销量
			
            //判断有没有实物商品
            if($v['is_shiwu'] == 1){
                //有实物商品,要填地址
                $this->is_shiwu = 1;
            }
            $sj_gnums +=  $v['num'];
        }
    
        //添加收货地址到数据库
        $delivery_data = $this->_get_delivery_data();
        if(empty($delivery_data)){
            //判断是否是实物商品
            if($this->is_shiwu == 1){
                return_json(1,"请检查收货地址");
            }else{
                return_json(1,"请检查信息是否填写正确");
            }
        }
    
        $delivery_data['uid'] = $this->uid;
         
        //插入数据库
        $dres = $this->deliveryModel->addDelivery($delivery_data);
    
        $delivery_data['id'] = $dres;
    
        $order_data = $this->_get_order_data($goods_info,$delivery_data);//获取订单信息
        if($order_data['pay_money']>0 && $goods_info[0]['gtype_id']==9) {
            return_json(1,'必须全额使用积分支付');
        }
        
        $order_data['sj_gnums'] = $sj_gnums;
        $order_data['goods_ids'] = implode(",",$goods_ids);//商品id,多个用逗号分割
        $order_data['goods_names'] = implode(",",$goods_names);//订单所有商品名称和编号的综合，用于做查询
        $order_data['goods_sale'] = implode(";",$goods_sale);//id和销量组合，用作统计销量
        
        $order_data['noyongjin_money'] = $noyongjin_money;//不参与分佣的特殊金额
    
        //查找该订单属于哪个皇冠
//        $king_userinfo = $this->_get_kinginfo($memberinfo);
//        if($king_userinfo){
//            $order_data['king_uid'] = $king_userinfo['uid'];
//            $order_data['king_realname'] = $king_userinfo['realname'];
//        }
        //将数据插入到订单表
        $order_id = $this->orderModel->addOrder($order_data);
    
        if($order_id){
            //删除购物车商品
            $cart_del = array(
                "uid" => $this->uid,
                "goods_id" => array(
                    "IN",$goods_ids
                )
            );
            $this->cartModel->where($cart_del)->delete();
            
            //扣除微币
            $order_data['order_id'] = $order_id;
            $this->_kou_score($order_data,$memberinfo);
    
            //判断还需不需要微信支付
            if($order_data['pay_money'] == 0 && ($order_data['pay_orgmoney']>0)){
                //不需要再次微信支付了
                //更改订单状态
                
                //$res = A("Ordercallback")->_changeOrder($order_data,2);//更改状态为已经支付
                $ordercallback = new OrdercallbackController();
                $res = $ordercallback->_changeOrder($order_data, 2);
                
                if(!$res){
                    return_json(1,"订单支付信息创建失败,请联系客服处理","","/mobile/orderdetail?order_id=".$order_id."&showwxpaytitle=1");
                }else{
                    return_json(0,"订单支付成功","","/mobile/orderdetail?order_id=".$order_id."&showwxpaytitle=1");
                }
            }
             
            return_json(0,"订单已提交,正在转入支付页面...","","/mobile/orderdetail?order_id=".$order_id."&showwxpaytitle=1");
        }
    
        return_json(1,"订单提交失败");
    }
    
    
    
    /*
     * 查找该用户的上级皇冠
     */
    protected function _get_kinginfo($memberinfo){
        
        if($memberinfo['grade_id']>=3){
            //他自己就是皇冠,返回空
            return false;
        }
        //他是皇冠等级之下的等级
        
        $refer_uid = $memberinfo['refer_uid'];//上一级的uid
        $refer_info = array();
        if($refer_uid){
            //查找上级信息
            $refer_info = $this->getMemberInfobyUid($refer_uid);
        }

        while(!empty($refer_info)){
            //上级信息存在
        
            if($refer_info['grade_id'] >=3 ){
                return $refer_info;
            }
        
            $refer_uid = $refer_info['refer_uid'];//上一级的uid
            $refer_info = $this->getMemberInfobyUid($refer_uid);//上一级的信息
        
            if($refer_info['uid'] == $memberinfo['uid']){
                break;//死循环,中断
            }
        
        }
        
        return false; 
    }
    
   
    protected function _money_msg($msg_user,$money,$mtype){
        $tmp_id = $this->tmpl['YUE']['tmp_id'];
        $color = $this->tmpl['YUE']['color'];
        if($mtype==1) {
            $url = get_domain()."/mobile/moneylists/money";
            $left = $msg_user['money']+$msg_user['lock_money'];
            $name = C('YONGJIN_NAME');
        }
        if($mtype==2) {
            $url = get_domain()."/mobile/moneylists/score";
            $left = $msg_user['score'];
            $name = C('SCORE_NAME');
        }
        if($mtype==3) {
            $url = get_domain()."/mobile/moneylists/cash";
            $left = $msg_user['cash_money'];
            $name = C('CASH_NAME');
        }
        if($mtype==4) {
            $url = get_domain()."/mobile/moneylists/stock";
            $left = $msg_user['stock'];
            $name = '库存';
        }
        $header = $name.'消费:'.$money.'\\n';
        $footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $msg_user['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($header),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($msg_user['nickname']),//昵称
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($left),//余额
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode(date("Y-m-d H:i:s")),//时间
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
        
        $msg_data = array(
            "uid" => $msg_user['uid'],
            "openid" => $msg_user['openid'],
            "nickname" => $msg_user['nickname'],
            "groupid" => -1,
            "content" => urldecode(json_encode($msg)),
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new \Mobile\Model\tmpmsgModel;
        $tmpmsgModel->addtmpmsg($msg_data);//添加消息到数据库队列
        return true;
    }

    public function baodan () {
        $allow = array(
            'order_type','realname','mobile','province','city','county','address','is_delivery','baodan_mobile',
            'is_cash','goods_id','number','grade_id','idcard','is_yongjin'
        );
        $data = param_filter($_POST, $allow);
        if($data['order_type']!=1) {
            return_json(1,'订单类型错误');
        }
        if(!$data['baodan_mobile']) {
            return_json(1,'请填写报单手机号');
        }
        if(!$data['grade_id']) {
            return_json(1,'请选择订单类型');
        }
        if($data['number']<0||!is_numeric($data['number'])) {
            return_json(1,'数量错误');
        }
        if($data['is_delivery']==1) {
            if(!$data['realname']) {
                return_json(1,'请填写姓名');
            }
            if(!$data['mobile']) {
                return_json(1,'请填写手机号');
            }
            if(!check_mobile($data['mobile'])) {
                //return_json(1,'手机号格式错误');
            }
            if(!$data['province']) {
                return_json(1,'请填写省');
            }
            if(!$data['city']) {
                return_json(1,'请填写市');
            }
            if(!$data['county']) {
                return_json(1,'请填写区');
            }
            if(!$data['address']) {
                return_json(1,'请填写详细地址');
            }
            $delivery = array(
                'delivery_name' => $data['realname'],
                'delivery_mobile' => $data['mobile'],
                'province' => $data['province'],
                'city' => $data['city'],
                'county' => $data['county'],
                'address' => $data['address']
            );
        }
        
        $baodaninfo = $this->memberModel->where(array('mobile'=>$data['baodan_mobile']))->field('uid,realname,nickname,grade_id,mobile,refer_uid')->find();
        if(!$baodaninfo) {
            //return_json(1,'报单用户不存在');
            if(!$data['realname'] || !$data['idcard']) {
                return_json(1,'请填写新报用户姓名和身份证号码');
            }
            
            //检查身份证
            $idcard = $data['idcard'];
            $len = strlen($idcard);
            if($len != 18){
                 return_json(1,"身份证号码填写错误,请重新填写");
            }
            $idcardold = $this->memberModel->where(array('idcard'=>$idcard))->find();
            if($idcardold) {
                return_json(1,'身份证号码已存在');
            }
            
        }
        if($baodaninfo['grade_id']>=5) {
            return_json(1,'你已报单，无法重复报单');
        }

        $goodsid = 1;
        if($data['goods_id']) {
            $goodsid = $data['goods_id'];
        }
        $goods = $this->goodsModel->where(array('goods_id'=>$goodsid))->find();
        $goods['num'] = $data['number'];
        $goods['shop_price'] = $goods['grade'.$data['grade_id'].'_price'];
        $moneyarr = $this->_getBaodanMoney($data,$goods);
        $allmoney = $moneyarr['goods_money']+$moneyarr['bzj_money']+$moneyarr['pxf_money'];

        $user = $this->memberinfo;
        $gradearr = M('grade')->getField('grade_id,grade_name');
        
        $numArr = array(
            2 => C('GRADE2_NUM')?C('GRADE2_NUM'):10,
            3 => C('GRADE3_NUM')?C('GRADE3_NUM'):50,
            4 => C('GRADE4_NUM')?C('GRADE4_NUM'):150,
            5 => C('GRADE5_NUM')?C('GRADE5_NUM'):480
        );
        
        $num = $numArr[$data['grade_id']];
        if($baodaninfo) {
            $num = $numArr[$data['grade_id']] - $numArr[$baodaninfo['grade_id']];
        }
        
        if($data['number']<$num) {
            return_json(1,$gradearr[$data['grade_id']]."需购买{$num}套");
        }
        
        $goodsinfo[] = $goods;
        $order = array(
            'uid' => $user['uid'],
            'baodan_uid' => $data['baodan_uid'],
            'realname' => $user['realname'],
            'nickname' => $user['realname'],
            'refer_uid' => $user['refer_uid'],
            'refer_nickname' => $user['refer_nickname'],
            'checked' => 0,
            'pay_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
            'order_title' => "报单升级",
            'delivery_mobile' => $data['baodan_mobile'],
            'delivery_name' => $data['realname'],
            'order_cashmoney' => $moneyarr['goods_money'],
            'pay_orgmoney' => $allmoney,
            'all_money' => $allmoney,
            'pay_money' => $allmoney,
            'bzj_money' => $moneyarr['bzj_money'],
            'pxf_money' => $moneyarr['pxf_money'],
            'goods' => serialize($goodsinfo),
            'order_type' => $data['order_type'],
            'sj_gnums' => $data['number'],
            'delivery' => serialize($delivery),
            'action_uid' => $this->uid,
            'order_sn' => 'WX'.date("YmdHis").sprintf("%05d", $user['uid']).rand(10,99),
            'province' => $data['province'],
            'city' => $data['city'],
            'county' => $data['county'],
            'goods_sale' => "{$goods['goods_id']},{$goods['num']}",
            'is_delivery' => $data['is_delivery'],
            'data_info' => json_encode($data),
            'order_ip' => get_client_ip()
        );
        $order = $this->_checkOrderData($order, $data);
        //可用于报单的数量增加
        //$this->memberModel->where(array('uid'=>$order['uid']))->setInc('canbaodan_number',$data['number']);
        $orderId = $this->orderModel->add($order);
        $order['order_id'] = $orderId;
        
        
        if($orderId) {
            
            if($order['pay_money'] == 0 && ($order['pay_orgmoney']>0)){
                //不需要再次微信支付了
                $ordercallback = new OrdercallbackController();
                $res = $ordercallback->_changeOrder($order, 2);
                if(!$res){
                    return_json(1,"订单支付信息创建失败,请联系客服处理","","/mobile/orderdetail?order_id=".$orderId."&showwxpaytitle=1");
                }else{
                    return_json(0,"订单支付成功","","/mobile/orderdetail?order_id=".$orderId."&showwxpaytitle=1");
                }
            }
             
            
            return_json(0,'提交成功，请稍等','','/mobile/orderdetail?order_id='.$orderId);
        }else{
            return_json(1,'失败请重试');
        }
    }
    
    public function getbuhuoprice () {
        $allow = array(
            'order_type','realname','mobile','province','city','county','address','is_delivery','baodan_mobile',
            'is_cash','goods_id','number','grade_id','idcard'
        );
        $data = param_filter($_POST, $allow);
        
        if($data['number']<0||!is_numeric($data['number'])) {
            return_json(1,'补货金额错误');
        }

        $grade = M('grade')->where(array('grade_id'=>$this->memberinfo['grade_id']))->find();
        $money = $data['number']*$grade['zhekou'];
        $money = round($money,2);

        return_json(0,'',$money);
    }

    public function getbaodanprice () {
        $allow = array(
            'order_type','realname','mobile','province','city','county','address','is_delivery','baodan_mobile',
            'is_cash','goods_id','number','grade_id','idcard'
        );
        $data = param_filter($_POST, $allow);
        $numArr = array(
            2 => C('GRADE2_NUM')?C('GRADE2_NUM'):10,
            3 => C('GRADE3_NUM')?C('GRADE3_NUM'):50,
            4 => C('GRADE4_NUM')?C('GRADE4_NUM'):150,
            5 => C('GRADE5_NUM')?C('GRADE5_NUM'):480
        );
        if($data['grade_id']) {
            $data['number'] = $numArr[$data['grade_id']];
        }
        
        $baodaninfo = $this->memberModel->where(array('mobile'=>$data['baodan_mobile']))->find();
        if($baodaninfo) {
            $data['number'] = $numArr[$data['grade_id']]-$numArr[$baodaninfo['grade_id']];
        }
      
        if($data['number']<0||!is_numeric($data['number'])) {
            return_json(1,'数量错误');
        }

        $goodsid = 1;
        if($data['goods_id']) {
            $goodsid = $data['goods_id'];
        }
        $goods = $this->goodsModel->where(array('goods_id'=>$goodsid))->find();
        $goods['num'] = $data['number'];
        $goods['shop_price'] = $goods['grade'.$data['grade_id'].'_price'];
        $moneyarr = $this->_getBaodanMoney($data,$goods);
        $moneyarr['number'] = $data['number'];
        return_json(0,'',$moneyarr);
    }
   

    /*
    * 报单订单价
    */
    protected function _getBaodanMoney ($data,$goods) {
        
        $baodaninfo = $this->memberModel->where(array('mobile'=>$data['baodan_mobile']))->find();
        
        if($data['grade_id']<$baodaninfo['grade_id']) {
            return_json(1,'报单等级低于当前等级');
        }
        if($data['grade_id']==$baodaninfo['grade_id']) {
            return_json(1,'报单等级等于当前等级');
        }
        $bzj = 0;
        $pxf = 0;
        switch($data['grade_id']) {
            case 2: $bzj=0;break;
            case 3: $bzj=0;break;
            case 4: $bzj=C('GRADE4_BZJ');$pxf=C('GRADE4_PXF');break;
            case 5: $bzj=C('GRADE5_BZJ');$pxf=C('GRADE5_PXF');break;
            default:$bzj=0;
        }
        if($baodaninfo) {
            $bzj -= $baodaninfo['bzj_money'];
            $pxf -= $baodaninfo['pxf_money'];
        }
       
        $goodsmoney = $goods['shop_price']*$goods['num'];
        return array(
            'goods_money' => round($goodsmoney,2),
            'bzj_money' => round($bzj>0?$bzj:0,2),
            'pxf_money' => round($pxf>0?$pxf:0,2)
        );
    }
    
    
    protected function _addScoreLog($order) {
        if($order['score_money']<=1300) {
            return false;
        }
        $member = $this->memberModel->where(array('uid'=>$order['uid']))->find();
        $money = $order['score_money']-1300;
        $this->memberModel->where(array('uid'=>$order['uid']))->setInc('score',$money);
        $yue = $member['score']+$money;
        $money_log = array(
            "uid" => $member['uid'],
            "nickname" => $member['realname'],
            "logtype" => 1,//收入
            "mtype" => 2,//类型
            "money" => $money,
            "content" => '[报单][券转入]',
            "order_id" => $order['order_id'],
            "order_uid" => $order['uid'],
            "order_paymoney" => $order['order_cashmoney'],
            "order_nickname" => $order['realname']?$order['realname']:$order['nickname'],
            "pay_time" => $order['pay_time'],
            "create_time" => date("Y-m-d H:i:s"),
            "from_jibie" => '',
            "bili" => '',
            "cash_money" => $yue,
        );
        $this->moneylogModel->add($money_log);
    }


    /*
     * 统一的订单信息重组
     */
    protected function _checkOrderData ($order,$data) {
        if($data['is_yongjin']&&$this->memberinfo['money']>0) {
            if($this->memberinfo['money']>=$order['pay_money']) {
                $usemoney = $order['pay_money'];
                $order['yongjin_money'] = $usemoney;
                $order['pay_money'] = 0;
            }else{
                $usemoney = $this->memberinfo['money'];
                $order['yongjin_money'] = $usemoney;
                $order['pay_money'] -= $this->memberinfo['money'];
            }
            $this->_outMoneylog($usemoney, $order, 1);
           
        }
        //使用现金支付
        if($data['is_cash']&&$this->memberinfo['cash_money']>0) {
            if($this->memberinfo['cash_money']>=$order['pay_money']) {
                $usemoney = $order['pay_money'];
                $order['cash_money'] = $usemoney;
                $order['pay_money'] = 0;
            }else{
                $usemoney = $this->memberinfo['cash_money'];
                $order['cash_money'] = $usemoney;
                $order['pay_money'] -= $this->memberinfo['cash_money'];
            }
            $this->_outMoneylog($usemoney, $order, 3);
           
        }
        return $order;
    }
    
    public function tihuo () {
        $allow = array(
            'number','realname','mobile','province','city','county','address','smscode','goods_id'
        );
        $data = param_filter($_POST, $allow);
        
//        if(!$data['smscode']) {
//            return_json(1,'请填写验证码');
//        }
//        
//        if(session('SMSCODE')!=$data['smscode']) {
//            return_json(1,'验证码错误');
//        }
        
        if(!$data['realname']) {
            return_json(1,'请填写姓名');
        }
        if(!$data['mobile']) {
            return_json(1,'请填写手机号');
        }
        if(!check_mobile($data['mobile'])) {
            //return_json(1,'手机号格式错误');
        }
        if(!$data['number'] || $data['number']<=0 || !is_numeric($data['number'])) {
            return_json(1,'请填写数量');
        }
        if($data['number']%C('TIHUO_NUM')!=0) {
            return_json(1,"提货数量必须是".C('TIHUO_NUM')."的倍数");
        }
       
        if(!$data['province']) {
            return_json(1,'请填写省');
        }
        if(!$data['city']) {
            return_json(1,'请填写市');
        }
        if(!$data['county']) {
            return_json(1,'请填写区');
        }
        if(!$data['address']) {
            return_json(1,'请填写详细地址');
        }
        if($this->memberinfo['stock']<$data['number']) {
            return_json(1,'你的库存不足，无法提货');
        }
        $delivery = array(
            'delivery_name' => $data['realname'],
            'delivery_mobile' => $data['mobile'],
            'province' => $data['province'],
            'city' => $data['city'],
            'county' => $data['county'],
            'address' => $data['address']
        );
        $user = $this->memberinfo;
        $allmoney = 0;
        
        $goodsid = 1;
        if($data['goods_id']) {
            $goodsid = $data['goods_id'];
        }
        
        $goods = $this->goodsModel->where(array('goods_id'=>$goodsid))->find();
        $goods['num'] = $data['number'];
        $goodsinfo[] = $goods;
        $order = array(
            'uid' => $user['uid'],
            'realname' => $user['realname'],
            'nickname' => $user['realname'],
            'refer_uid' => $user['refer_uid'],
            'refer_nickname' => $user['refer_nickname'],
            'checked' => 1,
            'pay_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
            'order_title' => "提货",
            'delivery_mobile' => $data['mobile'],
            'delivery_name' => $data['realname'],
            'pay_orgmoney' => $allmoney,
            'all_money' => $allmoney,
            'goods' => serialize($goodsinfo),
            'order_type' => 3,
            'sj_gnums' => 0,
            'delivery' => serialize($delivery),
            'action_uid' => $this->uid,
            'order_sn' => 'WX'.date("YmdHis").sprintf("%05d", $user['uid']).rand(10,99),
            'province' => $data['province'],
            'city' => $data['city'],
            'county' => $data['county'],
            'goods_sale' => "{$goods['goods_id']},{$goods['num']}"
        );
        //可用于报单的数量增加
        //$this->memberModel->where(array('uid'=>$order['uid']))->setInc('canbaodan_number',$data['number']);
        $orderId = $this->orderModel->add($order);
        $order['order_id'] = $orderId;
        if($orderId) {
            //TODO库存变动log
            $this->_outMoneylog($data['number'], $order, 4);
            return_json(0,'提货完成','','/mobile/orderlists/');
        }else{
            return_json(1,'提货失败请重试');
        }
    }
    
    public function buhuo () {
        $allow = array(
            'order_type','realname','mobile','province','city','county','address','number','is_delivery','is_cash','goods_id','is_yongjin'
        );
        $data = param_filter($_POST, $allow);
//        if(!$data['smscode']) {
//            return_json(1,'请填写验证码');
//        }
//        if(session('SMSCODE')!=$data['smscode']) {
//            return_json(1,'验证码错误');
//        }
        
      
        if(!$data['number']) {
            return_json(1,'请填写补货金额');
        }
        if($data['number']<=0 || $data['number']%C('BUHUO_NUM')!=0) {
            return_json(1,"补货金额必须是".C('BUHUO_NUM')."的倍数");
        }
        if($data['is_delivery']==1) {
            if(!$data['realname']) {
                return_json(1,'请填写姓名');
            }
            if(!$data['mobile']) {
                return_json(1,'请填写手机号');
            }
            if(!check_mobile($data['mobile'])) {
                //return_json(1,'手机号格式错误');
            }
            if(!$data['province']) {
                return_json(1,'请填写省');
            }
            if(!$data['city']) {
                return_json(1,'请填写市');
            }
            if(!$data['county']) {
                return_json(1,'请填写区');
            }
            if(!$data['address']) {
                return_json(1,'请填写详细地址');
            }
            $delivery = array(
                'delivery_name' => $data['realname'],
                'delivery_mobile' => $data['mobile'],
                'province' => $data['province'],
                'city' => $data['city'],
                'county' => $data['county'],
                'address' => $data['address']
            );
        }
        
        $user = $this->memberinfo;

        $grade = M('grade')->where(array('grade_id'=>$this->memberinfo['grade_id']))->find();
        $money = $data['number']*$grade['zhekou'];
        $money = round($money,2);

        $goods = array(
            'goods_name' => '补货订单',
            'num' => 1,
            'shop_price' => $money
        );
       
       

        $allmoney = $money;
        $goodsinfo[] = $goods;
        $order = array(
            'uid' => $user['uid'],
            'realname' => $user['realname'],
            'nickname' => $user['realname'],
            'refer_uid' => $user['refer_uid'],
            'refer_nickname' => $user['refer_nickname'],
            'checked' => 0,
            'pay_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
            'order_title' => "补货",
            'delivery_mobile' => $data['mobile'],
            'delivery_name' => $data['realname'],
            'pay_orgmoney' => $allmoney,
            'order_cashmoney' => $allmoney,
            'stock_money' => $data['number'],
            'all_money' => $allmoney,
            'pay_money' => $allmoney,
            'goods' => serialize($goodsinfo),
            'order_type' => $data['order_type'],
            'sj_gnums' => $data['number'],
            'delivery' => serialize($delivery),
            'action_uid' => $this->uid,
            'order_sn' => 'WX'.date("YmdHis").sprintf("%05d", $user['uid']).rand(10,99),
            'province' => $data['province'],
            'city' => $data['city'],
            'county' => $data['county'],
            'goods_sale' => "{$goods['goods_id']},{$goods['num']}",
            'is_delivery' => $data['is_delivery']
        );
        $order = $this->_checkOrderData($order, $data);
        
        //可用于报单的数量增加
        $orderId = $this->orderModel->add($order);
        $order['order_id'] = $orderId;
        if($orderId) {
            if($order['pay_money'] == 0 && ($order['pay_orgmoney']>0)){
                //不需要再次微信支付了
                $ordercallback = new OrdercallbackController();
                $res = $ordercallback->_changeOrder($order, 2);
                if(!$res){
                    return_json(1,"订单支付信息创建失败,请联系客服处理","","/mobile/orderdetail?order_id=".$orderId."&showwxpaytitle=1");
                }else{
                    return_json(0,"订单支付成功","","/mobile/orderdetail?order_id=".$orderId."&showwxpaytitle=1");
                }
            }
            return_json(0,'提交成功，请稍等','','/mobile/orderdetail?order_id='.$orderId);
        }else{
            return_json(1,'失败请重试');
        }
    }
    
    
    public function transfer () {
        $allow = array(
            'number','shouhuo_uid'
        );
        $data = param_filter($_POST, $allow);
        
        if(!$data['number'] || $data['number']<=0 || !is_numeric($data['number'])) {
            return_json(1,'请填写数量');
        }
        if($data['number']<10) {
            return_json(1,'拨货10盒起');
        }
        
        $shouhuoinfo = $this->memberModel->where(array('uid'=>$data['shouhuo_uid']))->find();
        if(!$shouhuoinfo) {
            return_json(1,'收货人不存在,请核实ID');
        }
        if($shouhuoinfo['grade_id']>$this->memberinfo['grade_id']) {
            return_json(1,'不能拨货给高于您等级的用户');
        }
       
        if($this->memberinfo['stock']<$data['number']) {
            return_json(1,'你的库存不足，无法拨货');
        }
        $user = $this->memberinfo;

        //本人扣库存
        $this->memberModel->where(array('uid'=>$user['uid']))->setDec('stock',$data['number']);
        $money_log = array(
            "uid" => $user['uid'],
            "nickname" => $user['realname']?$user['realname']:$user['nickname'],
            "logtype" => 0,//收入 1收入 0支出
            "mtype" => 4,//类型
            "money" => $data['number'],
            "content" => "【拨货库存变动】收货人:".($shouhuoinfo['realname']?$shouhuoinfo['realname']:$shouhuoinfo['nickname']),
            "order_uid" => $user['uid'],
            "create_time" => date("Y-m-d H:i:s"),//写流水的时间
            "un_lock" => 1,//不锁定,立即扣除 1解锁,0锁定
            "cash_money" => $user['stock']-$data['number']
        );
        $res = $this->moneylogModel->addMoneylog($money_log);
        
        $this->memberModel->where(array('uid'=>$shouhuoinfo['uid']))->setInc('stock',$data['number']);
        $money_log = array(
            "uid" => $shouhuoinfo['uid'],
            "nickname" => $shouhuoinfo['realname']?$shouhuoinfo['realname']:$shouhuoinfo['nickname'],
            "logtype" => 1,//收入 1收入 0支出
            "mtype" => 4,//类型
            "money" => $data['number'],
            "content" => "【拨货库存变动】拨货人:".($user['realname']?$user['realname']:$user['nickname']),
            "order_uid" => $shouhuoinfo['uid'],
            "create_time" => date("Y-m-d H:i:s"),//写流水的时间
            "un_lock" => 1,//不锁定,立即扣除 1解锁,0锁定
            "cash_money" => $shouhuoinfo['stock']+$data['number']
        );
        $res = $this->moneylogModel->addMoneylog($money_log);
        return_json(0,'拨货成功','','/mobile/orderlists/');
    }
    
}